package tech.mobi.child;


import java.util.ArrayList;
import java.util.HashMap;

import tech.mobi.child.adapter.GoodClientListAdapter;
import tech.mobi.child.base.BaseAct;
import tech.mobi.child.bean.GroupBean;
import tech.mobi.child.service.MainService;
import tech.mobi.child.utils.Configuration;
import tech.mobi.child.utils.OSCPullToRefreshListView;
import tech.mobi.child.utils.OSCPullToRefreshListView.OnRefreshListener;
import tech.mobi.child.utils.Task;
import tech.mobi.child.utils.TaskType;
import tech.mobi.child.utils.Tools;
import tech.mobi.child.utils.User;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


public class GoodClientListAct extends BaseAct implements OnClickListener {

	private ImageView ivBack;
	private TextView tvTitle;
	private ProgressBar progress;
	
	private OSCPullToRefreshListView listView = null;
	private GoodClientListAdapter<GroupBean> adapter;
	private ArrayList<GroupBean> groupList = new ArrayList<GroupBean>();
	private LinearLayout llLoading;
	private RelativeLayout rlLoading;
	private Button btnReload;
//	private ArrayList<GroupBean> data;
//	private LayoutInflater inflater;

	public static int currentPageNumber = 1;
	private String strCacheKey = "KeyGoodClientList";
	private String strType = "%";
	private String strOrder = "ZXFB";
	private String strWhere = "";
	
	private View lvQuestion_footer;
	private TextView lvQuestion_foot_more;
	private ProgressBar lvQuestion_foot_progress;
	
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.good_client_list_main);
		User.userName = "13731525124";
		ivBack = (ImageView) this.findViewById(R.id.ivBack);
		ivBack.setOnClickListener(this);
		progress = (ProgressBar) this.findViewById(R.id.progress);
		tvTitle = (TextView) this.findViewById(R.id.tvTitle);		
		tvTitle.setText("商品列表");
		
		strCacheKey = strCacheKey+"";
		
		// 正在获取信息 和 获取信息按钮 集合
		llLoading = (LinearLayout) this.findViewById(R.id.llLoading);
		rlLoading = (RelativeLayout) this.findViewById(R.id.rlLoading); // 正在获取信息
																		// 集合
		btnReload = (Button) this.findViewById(R.id.btnReload); // 获取信息 按钮
		btnReload.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				btnReload.setVisibility(View.GONE);
				rlLoading.setVisibility(View.VISIBLE);
				initData();
			}
		});
		currentPageNumber = 1;

		groupList = (ArrayList<GroupBean>) MainService
				.getCacheData(User.userName + this.strCacheKey);
		if (groupList == null) {
			setClickEnable(false);
			initData();
		} else {
			initGroupListView();
			llLoading.setVisibility(View.GONE);
			String updateTime = MainService.getCacheDataTime(User.userName
					+ this.strCacheKey);
			this.adapter.addData(groupList);
			//new Date().toLocaleString()
			this.listView.onRefreshComplete(getString(R.string.pull_to_refresh_update) + updateTime);
			this.listView.setSelection(0);
			
			if(groupList.size()==0) {
				listView.setTag(4);
				lvQuestion_foot_more.setText(R.string.load_empty);
			} else if(groupList.size()<Integer.parseInt(Configuration.PAGE_SIZE)) {
				listView.setTag(3); //UIHelper.LISTVIEW_DATA_FULL size < 10
				adapter.notifyDataSetChanged();
				lvQuestion_foot_progress.setVisibility(View.GONE);
				lvQuestion_foot_more.setText(R.string.load_full);
			} else if (groupList.size()>=Integer.parseInt(Configuration.PAGE_SIZE)){
				listView.setTag(1);
				adapter.notifyDataSetChanged();
				lvQuestion_foot_more.setText(R.string.load_more);
			}
			
		}

	}

	private void initGroupListView() {
		if (listView == null) {
			
			listView = (OSCPullToRefreshListView) this.findViewById(R.id.listView);
			final ArrayList<GroupBean> groupList = new ArrayList<GroupBean>();
			adapter = (GoodClientListAdapter<GroupBean>) new GoodClientListAdapter<GroupBean>(
					groupList, listView, this,"","");
			
	        lvQuestion_footer = getLayoutInflater().inflate(R.layout.osc_listview_footer, null);
	        lvQuestion_foot_more = (TextView)lvQuestion_footer.findViewById(R.id.listview_foot_more);
	        lvQuestion_foot_progress = (ProgressBar)lvQuestion_footer.findViewById(R.id.listview_foot_progress);
	        listView.addFooterView(lvQuestion_footer);//添加底部视图  必须在setAdapter前
			listView.setAdapter(adapter);

			
//			listView.setOnClickFooterListener(new OnClickFooterListener() {
//
//				@SuppressWarnings("unchecked")
//				public void onGerMore() {
//					ArrayList<GroupBean> data = (ArrayList<GroupBean>) (MainService
//							.getCacheData(User.userName + strCacheKey));
//					int size = data.size();
//					// TODO 需要修改“修改时间”
//					String updateTime = "";
//					if (size >= 1) {
//						updateTime = data.get(size - 1).releasetime;
//					}
//					if (GoodClient.strCurrCount != null && !"".equals(GoodClient.strCurrCount)) {
//						currentPageNumber = Integer.parseInt(GoodClient.strCurrCount);
//					}
//					setClickEnable(false);
//					HashMap<String, String> map = new HashMap<String, String>();
//					map.put(MainAct.USER_NAME, User.userName);
//					map.put(MainAct.CURRENT_PAGE_NUMBER, currentPageNumber + "");
//					map.put(MainAct.PAGE_SIZE, Configuration.PAGE_SIZE);
//					map.put(MainAct.LASTET_UPDATE_TIME, updateTime);
//					map.put(MainAct.IS_MORE, "more");// more-代表获取更多信息，notmore－代表下拉刷新获取数据
//					map.put("typeid", strType);
//					map.put("orderid", strOrder);
//					map.put("wheretext", strWhere);
//					map.put("clientVersion", getClientVersionNumber());
//					Task task = new Task(TaskType.TASK_GOOD_CLIENT_LIST_MORE,
//							map);
//					MainService.newTask(task);
//				}
//			});

			listView.setOnScrollListener(new AbsListView.OnScrollListener() {
				public void onScrollStateChanged(AbsListView view, int scrollState) {
					listView.onScrollStateChanged(view, scrollState);
					
					//数据为空--不用继续下面代码了
					if(groupList.size() == 0) return;
					
					//判断是否滚动到底部
					boolean scrollEnd = false;
					try {
						if(view.getPositionForView(lvQuestion_footer) == view.getLastVisiblePosition())
							scrollEnd = true;
					} catch (Exception e) {
						scrollEnd = false;
					}
					
					int lvDataState = Tools.toInt(listView.getTag());
					if(scrollEnd && lvDataState==1)
					{
						listView.setTag(2);
						lvQuestion_foot_more.setText(R.string.load_ing);
						lvQuestion_foot_progress.setVisibility(View.VISIBLE);
						//  获取更多
						@SuppressWarnings("unchecked")
						ArrayList<GroupBean> data = (ArrayList<GroupBean>) (MainService
								.getCacheData(User.userName + strCacheKey));
						int size = data.size();
						// TODO 需要修改“修改时间”
						String updateTime = "";
						if (size >= 1) {
							updateTime = data.get(size - 1).releasetime;
						}
						if (GoodClient.strCurrCount != null && !"".equals(GoodClient.strCurrCount)) {
							currentPageNumber = Integer.parseInt(GoodClient.strCurrCount);
						}
						setClickEnable(false);
						HashMap<String, String> map = new HashMap<String, String>();
						map.put("a", User.userName);
						map.put("c", currentPageNumber + "");
						map.put("d", Configuration.PAGE_SIZE);
						map.put("e", updateTime);
						map.put("b", "more");// more-代表获取更多信息，notmore－代表下拉刷新获取数据
						map.put("typeid", strType);
						map.put("orderid", strOrder);
						map.put("wheretext", strWhere);
						map.put("clientVersion", getClientVersionNumber());
						Task task = new Task(TaskType.TASK_GOOD_CLIENT_LIST_MORE,
								map);
						MainService.newTask(task);
					}
				}
				public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
					listView.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
				}
			});
			
			listView.setOnRefreshListener(new OnRefreshListener() {

				public void onRefresh() {
					setClickEnable(false);
					// TODO 需要修改“修改时间”
					String updateTime = MainService
							.getCacheDataTime(User.userName + strCacheKey);
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("a", User.userName);
					map.put("c", "1");
					map.put("d", Configuration.PAGE_SIZE);
					map.put("e", updateTime);
					map.put("b", "notmore");// more-代表获取更多信息，notmore－代表下拉刷新获取数据
					map.put("typeid", strType);
					map.put("orderid", strOrder);
					map.put("wheretext", strWhere);
					map.put("clientVersion", getClientVersionNumber());
					Task task = new Task(TaskType.TASK_GOOD_CLIENT_LIST_LATEST,
							map);
					MainService.newTask(task);
				}
			});
		}
	}

	public void initData() {
		setClickEnable(false);
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("a", User.userName);
		map.put("c", currentPageNumber + "");
		map.put("d", Configuration.PAGE_SIZE);
		map.put("e", "0");// 0-代表第一次请求数据
		map.put("b", "1");// more-代表获取更多信息，notmore－代表下拉刷新获取数据
		map.put("typeid", strType);
		map.put("orderid", strOrder);
		map.put("wheretext", strWhere);
		map.put("clientVersion", getClientVersionNumber());
		Task task = new Task(TaskType.TASK_GOOD_CLIENT_LIST_INIT, map);
		MainService.newTask(task);
	}

	@Override
	public void init() {

	}

	@SuppressWarnings("unchecked")
	@Override
	public void refresh(Object... param) {
		stopProgress();
		String isLastPage = "true";
		String updateTime = "";
		int type_id = (Integer) param[0];
		switch (type_id) {
		case TaskType.TASK_GOOD_CLIENT_LIST_INIT: // 首次加载刷新
			// TODO 首次加载进行数据刷新操作
			setClickEnable(true);
			try {
				HashMap<String, Object> map = (HashMap<String, Object>) param[1];
				if (map.size() == 2) {
					llLoading.setVisibility(View.GONE);
					HashMap<String, Object> map1 = new HashMap<String, Object>();
					map1.put(MainAct.LAST_UPDATE_DATE, "");
					map1.put(MainAct.LAST_UPDATE_DATA,
							new ArrayList<GroupBean>());
					MainService.newCacheData(User.userName + this.strCacheKey,
							map1);

					initGroupListView();
					updateTime = map.get("updatetime").toString();
					MainService.updateCacheDataTime(User.userName
							+ this.strCacheKey, updateTime);
					isLastPage = loadData((ArrayList<GroupBean>) map
							.get("data"));

					
					this.listView.onRefreshComplete(getString(R.string.pull_to_refresh_update) + updateTime);
					this.listView.setSelection(0);
					
					ArrayList<GroupBean> groupList = (ArrayList<GroupBean>) map
					.get("data");
					if(groupList.size()==0) {
						listView.setTag(4);
						lvQuestion_foot_more.setText(R.string.load_empty);
					} else if(groupList.size()<Integer.parseInt(Configuration.PAGE_SIZE)) {
						listView.setTag(3); //UIHelper.LISTVIEW_DATA_FULL size < 10
						adapter.notifyDataSetChanged();
						lvQuestion_foot_progress.setVisibility(View.GONE);
						lvQuestion_foot_more.setText(R.string.load_full);
					} else if (groupList.size()>=Integer.parseInt(Configuration.PAGE_SIZE)){
						listView.setTag(1);
						adapter.notifyDataSetChanged();
						lvQuestion_foot_more.setText(R.string.load_more);
					}
					
					
				} else {
					rlLoading.setVisibility(View.GONE);
					btnReload.setVisibility(View.VISIBLE);
//					Toast.makeText(this, "网络环境不好，请稍候再试", Toast.LENGTH_LONG)
//							.show();
				}
			} catch (Exception ex) {

			}
			break;
		case TaskType.TASK_GOOD_CLIENT_LIST_LATEST: // 点击刷新
			setClickEnable(true);
			try {
				// TODO 点击获取最新进行数据刷新操作
				HashMap<String, Object> map2 = (HashMap<String, Object>) param[1];
				if (map2.size() == 2) {
					updateTime = map2.get("updatetime").toString();
					MainService.updateCacheDataTime(User.userName
							+ this.strCacheKey, updateTime);
//					groupList = new ArrayList<GroupBean>(); 
					ArrayList<GroupBean> groupList = (ArrayList<GroupBean>) map2
							.get("data");
					if (groupList.size() > 0) {
						if (groupList.size() == Integer
								.parseInt(Configuration.PAGE_SIZE)) {
							// All
							MainService.clearCacheData(User.userName
									+ this.strCacheKey);
							MainService.insertCacheData(User.userName
									+ this.strCacheKey, groupList, updateTime);

							this.adapter.clearData();
							this.adapter.insertData(groupList);
							currentPageNumber = 1;
						} else {
							// not All
							MainService.insertCacheData(User.userName
									+ this.strCacheKey, groupList, updateTime);
							this.adapter.insertData(groupList);
						}
						Toast.makeText(this, "更新" + groupList.size() + "条信息",
								Toast.LENGTH_SHORT).show();
					} else {

						Toast.makeText(this, "没有新信息", Toast.LENGTH_SHORT)
								.show();
					}
				} else {
//					Toast.makeText(this, "网络环境不好，请稍候再试", Toast.LENGTH_LONG)
//							.show();
				}
				this.listView.onRefreshComplete(updateTime);
				this.listView.setSelection(0);
			} catch (Exception ex) {

			}
			break;

		case TaskType.TASK_GOOD_CLIENT_LIST_MORE: // 获取更多
			setClickEnable(true);
			try {
				// TODO 点击获取更多进行数据刷新操作
				HashMap<String, Object> map1 = (HashMap<String, Object>) param[1];
				if (map1.size() == 2) {
					isLastPage = loadData((ArrayList<GroupBean>) map1
							.get("data"));
					
					if(((ArrayList<GroupBean>) map1
							.get("data")).size()<Integer.parseInt(Configuration.PAGE_SIZE)) {
						listView.setTag(3); //UIHelper.LISTVIEW_DATA_FULL size < 10
						adapter.notifyDataSetChanged();
						lvQuestion_foot_progress.setVisibility(View.GONE);
						lvQuestion_foot_more.setText(R.string.load_full);
					} else if (((ArrayList<GroupBean>) map1
							.get("data")).size()>=Integer.parseInt(Configuration.PAGE_SIZE)){
						listView.setTag(1);
						adapter.notifyDataSetChanged();
						lvQuestion_foot_more.setText(R.string.load_more);
					}
				}
			} catch (Exception ex) {

			}
			break;
		}

	}


	@SuppressWarnings("unchecked")
	public String loadData(ArrayList<GroupBean> groupList) {
		String isLastPage = "true";

		if (groupList.size() > 0) {
			MainService.addCacheData(User.userName + this.strCacheKey,
					groupList);
			this.adapter.addData(groupList);
			currentPageNumber++;
			GoodClient.strCurrCount = currentPageNumber +"";
			if (!(groupList.size() < Integer.parseInt(Configuration.PAGE_SIZE))) {
				isLastPage = "false";
			}
		}
		return isLastPage;
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.ivBack) {
			finish();
		} 

	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	private void setClickEnable(boolean bool) {
		ivBack.setEnabled(bool);
		if (bool) {
			this.progress.setVisibility(View.GONE);
		} else {
			this.progress.setVisibility(View.VISIBLE);
		}
		
	}

	public static class GoodClient {

		/**
		 * 订购
		 */
		public static String strTypeId = "";
		public static String strTypeName = "";

		public static String strOrderId = "";
		public static String strOrderName = "";
		
		public static String strCurrCount = "";
		
		public static boolean isOpen = false;

	}

}
